package com.browsesoft.adapter;

import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;

import com.browsesoft.ExtendElement;
import com.browsesoft.PropertiesService;
import com.browsesoft.SequenceFind;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.oa.BSMIMEParser;
import com.browsesoft.resource.UniversalResourceEntity;

/**
 * 文档模板
 */
public class DocumentTemplate extends UniversalResourceEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4406538432132990015L;

	BSMIMEParser parser;

	/**
	 * 空构造
	 */

	public DocumentTemplate() {
		super();
		try {
			// 产生id号
			String id = Integer.toString(SequenceFind.getID());
			attributes.put("id", id);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 使用属性构造
	 */
	public DocumentTemplate(Hashtable attrs) {
		super(attrs);
	}

	// 添加
	public void insert() throws Exception {
		// 写库
		DBTools.insert(this.getTableName(), this.getAttributes());
	}

	/**
	 * 页面服务
	 * 
	 * @throws Exception
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.service(request, response);
		if (action != null && action.equals("confirm")) {
			parser = (BSMIMEParser) request.getAttribute("parser");
			if (parser != null) {
				this.attributes.put("realname", parser.getRealName());
				this.attributes.put("blob_id", parser.getBlobID());
			}
		}
	}

	public String getFilePathName() throws Exception {
		String path = PropertiesService.getProperty("attackment", "path");
		path = path + this.attributes.get("savename");
		return path;
	}

	public String getBlobID() {
		return (String) this.attributes.get("blob_id");
	}

	public String getFileRealName() {
		return (String) this.attributes.get("realname");
	}

	/**
	 * 更新页面元素
	 * 
	 * @param hTMLBasicComponent
	 *            基本组件
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent hTMLBasicComponent)
			throws Exception {
		// 得到页面元素
		Element e = hTMLBasicComponent.getElement();
		// 找到要处理的元素
		Element add = (Element) ExtendElement.findElementsByTagName(e, "input",
				"name", "add").get(0);
		// 设置id号
		String onClick = add.getAttribute("onclick");
		onClick = onClick.replaceAll("parentid=", "parentid=" + this.getID());
		// 从社onclick的内容
		add.setAttribute("onclick", onClick);
	}
}
